import cv2

img = cv2.imread("./img/b.png")
mh,mw,md = img.shape
# 灰度化处理
gray_img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# 模糊处理(因为是简单图形的检测，不需要模糊)
ret,binary_img = cv2.threshold(gray_img,147,255,cv2.THRESH_BINARY)

# 寻找图形中的轮廓
contours,hierarchy = cv2.findContours(binary_img,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

# 直接绘制轮廓
# cv2.drawContours(img,contours,-1,color=(0,0,0),thickness=2)

# 通过检测到的轮廓，判断到底是什么图形？？？
for cont in contours:
    x, y, w, h = cv2.boundingRect(cont)
    if w > mw - 100 and h > mh - 100:
        continue
    else:
        cv2.rectangle(img,(x,y),(x+w,y+h),color=(0,0,0),thickness=2)
    #     # print(x,y,w,h)
    #
        peri = cv2.arcLength(cont, True)
        # 找近似的轮廓，例如：把0.04*周长的线段认为是一个边
        approx = cv2.approxPolyDP(cont, float(0.04) * peri, True)
# 展示原图
cv2.imshow("src",img)
cv2.waitKey(0)